package logic

import (
	"context"
	"errors"
	"fmt"
	"srv/models/mysqlinit"
	"srv/models/redisinit"

	"srv/internal/svc"
	"srv/srv"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *LoginLogic) Login(in *srv.LoginRequest) (*srv.LoginResponse, error) {
	// todo: add your logic here and delete this line
	u := mysqlinit.User{}
	err := u.FindUser(in.Account)
	if err != nil {
		logx.Error("获取用户详情失败")
		return nil, errors.New("获取用户详情失败")
	}
	if u.ID == 0 {
		u.Account = in.Account
		val := redisinit.Rdb.Get(context.Background(), "SendSms"+in.Account+"Login").Val()
		if in.SendSms != val {
			count, _ := redisinit.Rdb.Get(context.Background(), "SendSms"+in.Account+"Login").Int()
			if count >= 5 {
				redisinit.Rdb.Del(context.Background(), "errors_count")
				redisinit.Rdb.Del(context.Background(), "SendSms"+in.Account+"Login")

				logx.Error("验证码错误次数超过上限，请重新发送新的验证码")
				return nil, errors.New("验证码错误次数超过上限，请重新发送新的验证码")
			} else {
				redisinit.Rdb.Incr(context.Background(), "SendSms"+in.Account+"Login").Result()
				logx.Error("验证码错误")
				return nil, errors.New("验证码错误")
			}

		}

		err = u.CreateUser()
		if err != nil {
			logx.Error("用户注册失败")
			return nil, errors.New("用户注册失败")
		}
	} else {
		val := redisinit.Rdb.Get(context.Background(), "SendSms"+in.Account+"Login").Val()
		if val != in.SendSms {

			count, _ := redisinit.Rdb.Get(context.Background(), "errors_count").Int()
			fmt.Println(count)
			if count >= 5 {
				redisinit.Rdb.Del(context.Background(), "SendSms"+in.Account+"Login")
				redisinit.Rdb.Del(context.Background(), "errors_count")
				logx.Error("验证码错误次数超过上限，请重新发送新的验证码")
				return nil, errors.New("验证码错误次数超过上限，请重新发送新的验证码")
			} else {
				redisinit.Rdb.Incr(context.Background(), "SendSms"+in.Account+"Login").Result()
				logx.Error("验证码错误")
				return nil, errors.New("验证码错误")
			}
		}
	}
	return &srv.LoginResponse{
		UserId: int64(u.ID),
	}, nil
}
